package com.lynn.blog.controller;

import com.lynn.blog.common.ApiResponse;
import com.lynn.blog.dto.PostSaveDTO;
import com.lynn.blog.dto.PostUpdateDTO;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.lynn.blog.entity.Post;
import com.lynn.blog.service.PostService;

import java.util.List;

/**
 * Author: Lynn
 * Date: 2024/07/15 下午5:17
 */
@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Resource
    private PostService postService;

    @PostMapping
    public ApiResponse<Boolean> save(@Validated @RequestBody PostSaveDTO dto) {
        Boolean save = postService.savePost(dto);
        return save ? ApiResponse.success() : ApiResponse.error(500, "保存失败");
    }

    @GetMapping
    public ApiResponse<List<Post>> list(@RequestParam(value = "uid") Integer uid,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "createdAsc", defaultValue = "false") Boolean createdAsc) {
        return postService.listPosts(uid, pageNum, pageSize, createdAsc);
    }

    @GetMapping("/{id}")
    public ApiResponse<Post> getById(@PathVariable(value = "id") Integer id) {
        return ApiResponse.success(postService.getById(id));
    }

    @PutMapping("/{id}")
    public ApiResponse<Boolean> update(@PathVariable(value = "id") Integer id, @RequestBody PostUpdateDTO dto) {
        Boolean update = postService.updateByPostId(id, dto);
        return update ? ApiResponse.success() : ApiResponse.error(500, "更新失败");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> remove(@PathVariable(value = "id") Integer id) {
        return postService.removeById(id) ? ApiResponse.success() : ApiResponse.error(500, "删除失败");
    }
}
